#!/bin/bash

# 
# This script is an SMF method for tracking test client status
#

# sync definition of smf(5) exit status values
SMF_EXIT_OK=0
SMF_EXIT_ERR_NOSMF=99
# reset the value to keep service always in the correct status
#SMF_EXIT_ERR_FATAL=95
SMF_EXIT_ERR_FATAL=0

# SMF_FMRI should be provided by smf restarter
if [ -z "$SMF_FMRI" ]; then
    print -u2 "This script can only be invoked by smf(5)"
    exit $SMF_EXIT_ERR_NOSMF
fi

#
# Constant
#
DAEMONIZE_BNM="runserver_socketio"

#
# Function
#
# arg1: smf FMRI
# arg2: smf property name
# arg3: target var
function get_smf_prop () {
    eval "${3}=\"`svcprop -p ${2} ${1}`\""
}


#
# Main
#
typeset g_wox_root
typeset g_server
typeset g_port
typeset g_log
get_smf_prop ${SMF_FMRI} args/wox_root g_wox_root
get_smf_prop ${SMF_FMRI} args/server g_server
get_smf_prop ${SMF_FMRI} args/port g_port
get_smf_prop ${SMF_FMRI} args/log_file g_log

case "$1" in
  start)
    if (ps -ef | grep "${DAEMONIZE_BNM}" | grep -v 'grep' >/dev/null 2>&1); then
        print -u2 "ERROR: another instance already running"
        exit ${SMF_EXIT_ERR_FATAL}
    else
        # run the daemonize
        nohup python $g_wox_root/manage.py ${DAEMONIZE_BNM} ${g_server}:${g_port} > ${g_log} 2>&1 &
    fi
    ;;
  stop)
    # notify daemonize to terminate
    pids="`ps -ef | \
                grep "${DAEMONIZE_BNM}" 2>/dev/null | \
                grep -v 'grep' | \
                awk '{print $2}'  | sort -nr`"
    test -n "$pids" && kill $pids
    ;;
  refresh)
    # do nothing
    :
    ;;
  *)
    print -u2 "Usage: `basename $0` { start | stop | refresh }"
    exit ${SMF_EXIT_ERR_FATAL}
  ;;
esac

exit 0
